package com.wjl.picture.common.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.*;
import com.wjl.picture.common.exception.BusinessException;
import com.wjl.picture.common.exception.ErrorCode;
import com.wjl.picture.common.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

@Service
public class UrlPictureUpload extends PictureUploadTemplate{
    @Override
    protected void validPicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件不能为空");
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件url错误");
        }
        ThrowUtils.throwIf(!((fileUrl.startsWith("http://") || fileUrl.startsWith("https://"))), ErrorCode.PARAMS_ERROR, "仅支持http或者https");
        try (HttpResponse httpResponse = HttpUtil.createRequest(Method.HEAD, fileUrl).execute()) {
            if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            String contentType = httpResponse.header(Header.CONTENT_TYPE);
            final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
            ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                    ErrorCode.PARAMS_ERROR, "文件类型错误");
            String contentLength = httpResponse.header(Header.CONTENT_LENGTH);
            ThrowUtils.throwIf(StrUtil.isBlank(contentLength), ErrorCode.PARAMS_ERROR, "文件大小错误");
            long fileSize = NumberUtil.parseLong(contentLength);
            final long ONE_M = 1024 * 1024L;
            ThrowUtils.throwIf(fileSize > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件url错误");
        }
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        String fileUrl = (String) inputSource;
        return FileUtil.mainName(fileUrl);
    }

    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        String fileUrl = (String) inputSource;
        HttpUtil.downloadFile(fileUrl, file);
    }
}
